﻿using DT.GoogleAnalytics.Metro;
using FantasyWereld.Common;
using FantasyWereld.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.ApplicationModel.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234233

namespace FantasyWereld.Views
{
    /// <summary>
    /// A page that displays a collection of item previews.  In the Split Application this page
    /// is used to display and select one of the available groups.
    /// </summary>
    public sealed partial class AuthorOverviewPage : FantasyWereld.Common.LayoutAwarePage
    {
        public AuthorOverviewPage()
        {
            // Start cache 
            this.NavigationCacheMode = NavigationCacheMode.Enabled;

            this.InitializeComponent();
            FadeOpacity.Begin();

            //ObservableCollection<string> sortering = new ObservableCollection<string>();
            //sortering.Add("Sorteren op achternaam");
            //sortering.Add("Sorteren op voornaam");
            //sortering.Add("Sorteren op land");
            //sortOrder.DataContext = sortering;
            //sortOrder.SelectedItem = sortOrder.Items[0];

            try
            {
                // Read books from disk and fetch images
                FWDataSource.ReadBooksFromDisk(Constants.BOOKFEED_BD_CODE, false);
            }
            catch
            {
                // On error switch to offline mode
                FWDataSource.ReadBooksFromDisk(Constants.BOOKFEED_BD_CODE, true);
            }

            try
            {
                // Read authors from disk
                FWDataSource.ReadAuthorsFromDisk(false);
            }
            catch
            {
                // On error switch to offline mode
                FWDataSource.ReadAuthorsFromDisk(true);
            }

            List<FWDataSource.GroupInfoList<object>> dataLetter = FWDataSource.GetAuthorsByLetterSortedOnLastName();
            itemsViewSource.Source = dataLetter;
            (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = itemsViewSource.View.CollectionGroups;
        }

        // Start invalidate cache 
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            if (e.NavigationMode == NavigationMode.Back)
            {
                ResetPageCache();
            }
        }

        private void ResetPageCache()
        {
            var cacheSize = ((Frame)Parent).CacheSize;
            ((Frame)Parent).CacheSize = 0;
            ((Frame)Parent).CacheSize = cacheSize;
        }
        // end invalidate cache

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var group = FWDataSource.GetGroup((String)navigationParameter);
            this.DefaultViewModel["Group"] = group;
            this.DefaultViewModel["Items"] = group.Items;
        }

        /// <summary>
        /// Invoked when an item is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((FWDataItem)e.ClickedItem).UniqueId;
            this.Frame.Navigate(typeof(AuthorDetailPage), itemId);
        }

        /// <summary>
        /// Invoked when a user wants to browse to the FantasyWereld website.
        /// </summary>
        /// <param name="sender">Sender parameter is unused</param>
        /// <param name="e">Event data parameters is unused</param>
        private async void OnBrowseToSiteButtonClicked(object sender, RoutedEventArgs e)
        {
            // Create the URI to launch from a string. 
            var uri = new Uri(Constants.WEBSITEBASE);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Invoked when a user wants to browse to the FantasyWereld forum.
        /// </summary>
        /// <param name="sender">Sender parameter is unused</param>
        /// <param name="e">Event data parameters is unused</param>
        private async void OnBrowseToForumButtonClicked(object sender, RoutedEventArgs e)
        {
            // Create the URI to launch from a string. 
            var uri = new Uri(Constants.WEBSITE_FORUM);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Invoked when a user wants to browse to the FantasyWereld facebook page.
        /// </summary>
        /// <param name="sender">Sender parameter is unused</param>
        /// <param name="e">Event data parameters is unused</param>
        private async void OnBrowseToFacebookButtonClicked(object sender, RoutedEventArgs e)
        {
            // Create the URI to launch from a string. 
            var uri = new Uri(Constants.WEBSITE_FACEBOOK);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private void SearchBoxEventsSuggestionsRequested(object sender, SearchBoxSuggestionsRequestedEventArgs e)
        {
            string queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                SearchSuggestionCollection suggestionCollection = e.Request.SearchSuggestionCollection;

                string[] terms = FWDataSource.AllKeywords;

                foreach (var term in terms)
                {
                    if (term.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
                        suggestionCollection.AppendQuerySuggestion(term);
                }
            }
        }

        /// <summary>
        /// Called when query submitted in SearchBox
        /// </summary>
        /// <param name="sender">The Xaml SearchBox</param>
        /// <param name="e">Event when user submits query</param>
        private void SearchBoxEventsQuerySubmitted(object sender, SearchBoxQuerySubmittedEventArgs e)
        {
            var queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                // Load books if still necessary
                FWDataSource.LoadBooks();

                // If the Window isn't already using Frame navigation, insert our own Frame
                var previousContent = Window.Current.Content;
                var frame = previousContent as Frame;

                frame.Navigate(typeof(SearchResultsPage), queryText);
                Window.Current.Content = frame;

                // Google Analytics helper
                AnalyticsHelper.Setup();

                // Ensure the current window is active
                Window.Current.Activate();
            }
        }

        private void SearchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as SearchBox).Width = 250;
        }

        private void SearchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((sender as SearchBox).QueryText == "")
                (sender as SearchBox).Width = 35;
        }

        private void sortOrder_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int x = (sender as ComboBox).SelectedIndex;
            switch (x)
            {
                case 0 :
                    {
                        List<FWDataSource.GroupInfoList<object>> dataLetter = FWDataSource.GetAuthorsByLetterSortedOnLastName();
                        itemsViewSource.Source = dataLetter;
                        (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = itemsViewSource.View.CollectionGroups;
                        break;
                    }
                case 1 :
                    {
                        List<FWDataSource.GroupInfoList<object>> dataLetter = FWDataSource.GetAuthorsByLetterSortedOnFirstName();
                        itemsViewSource.Source = dataLetter;
                        (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = itemsViewSource.View.CollectionGroups;
                        break;
                    }
                case 2 :
                    {
                        List<FWDataSource.GroupInfoList<object>> dataLetter = FWDataSource.GetAuthorsByLetterSortedOnCountry();
                        itemsViewSource.Source = dataLetter;
                        (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = itemsViewSource.View.CollectionGroups;
                        itemsViewSource.ItemsPath = new PropertyPath("GetAllAuthorsSortedOnCountry");

                        break;
                    }
            }
        }
    }
}